#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcdn.request.v20141111 import DescribeUserDomainsRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models

API="https://oapi.dingtalk.com/robot/send?access_token=07133fed0a8d1c70c34c279653967514ced6f3b3de194b5824250218f9034cef"
zone_list=['cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-hangzhou','cn-shanghai','cn-shenzhen']

def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        get_cdndomain(account)

def get_cdndomain(account):
    client = AcsClient(account.access_id,account.access_secret)
    request = DescribeUserDomainsRequest.DescribeUserDomainsRequest()
    request.set_accept_format('json')
    request.add_query_param('DomainStatus', 'online')
    response = client.do_action_with_exception(request).decode('utf-8')
    response=json.loads(response)
    if len(response['Domains']['PageData']):
        domain_list=response['Domains']['PageData']
        delete_cdndomain(domain_list,account)
        for domain in domain_list:
            try:
                cdnobj=models.CDNDomain.objects.get(domain_name=domain['DomainName'])
                cdnobj.account=account
                cdnobj.ishttps=0 if domain['SslProtocol']=='off' else 1
                cdnobj.cname=domain['Cname']
                cdnobj.source=','.join(domain['Sources']['Source'])
            except Exception as e:
                if domain['SslProtocol']=='off':
                    cdnobj=models.CDNDomain(domain_name=domain['DomainName'],ishttps=0,account=account,source=",".join(domain['Sources']['Source']),cname=domain['Cname'])
                else:
                    cdnobj=models.CDNDomain(domain_name=domain['DomainName'],ishttps=1,account=account,source=",".join(domain['Sources']['Source']),cname=domain['Cname'])
            finally:
                cdnobj.save()



def delete_cdndomain(domain_list,account):
    new_domain_list=[domain['DomainName'] for domain in domain_list]
    old_domain_list_1=models.CDNDomain.objects.filter(account=account)
    old_domain_list=[domain.domain_name for domain in old_domain_list_1]
    for domain in old_domain_list:
        if domain not in new_domain_list:
            models.CDNDomain.objects.get(domain_name=domain).delete()


if __name__=='__main__':
    main()
